const Router = require('koa-router');
const router = new Router();
const pool = require('../db');

// 获取播放列表详情
router.get('/playlists/:id', async (ctx) => {
  const { id } = ctx.params;
  try {
    // 检查播放列表是否存在
    const [playlists] = await pool.execute(
      'SELECT * FROM playlists WHERE id = ?', 
      [id]
    );
    
    if (playlists.length === 0) {
      ctx.status = 404;
      ctx.body = { code: -1, message: '播放列表不存在' };
      return;
    }

    // 获取歌曲列表
    const [songs] = await pool.execute(`
      SELECT s.* FROM songs s
      JOIN playlist_songs ps ON s.id = ps.song_id
      WHERE ps.playlist_id = ?
      ORDER BY ps.sort_order
    `, [id]);

    ctx.body = {
      code: 0,
      data: {
        ...playlists[0],
        songs: songs,
        song_count: songs.length
      }
    };
  } catch (err) {
    console.error('获取播放列表失败:', err);
    ctx.status = 500;
    ctx.body = { code: -1, message: '服务器错误' };
  }
});

// 获取单个歌单信息
router.get('/playlists/:id', async (ctx) => {
    try {
        const [rows] = await pool.execute('SELECT * FROM playlists WHERE id = ?', [ctx.params.id]);
        if (rows.length > 0) {
            ctx.body = { code: 0, data: rows[0] };
        } else {
            ctx.body = { code: 404, message: 'Playlist not found' };
        }
    } catch (error) {
        ctx.body = { code: 500, message: error.message };
    }
});

// 获取歌单的歌曲列表
router.get('/playlists/:id/songs', async (ctx) => {
    try {
        const [rows] = await pool.execute(`
            SELECT s.* FROM songs s
            JOIN playlist_songs ps ON s.id = ps.song_id
            WHERE ps.playlist_id = ?
        `, [ctx.params.id]);
        ctx.body = { code: 0, data: rows };
    } catch (error) {
        ctx.body = { code: 500, message: error.message };
    }
});

module.exports = router;